import datetime
from django.contrib.auth.models import User
from django.db import models

class Topic(models.Model):
    title = models.CharField(max_length=140,help_text='Maximum 140 characters.')
    gross = models.IntegerField(editable=False,default=0)
    class Meta:
        ordering = ["title"]
        verbose_name_plural = "Topics"
        
    def __unicode__(self):
        return self.title
    
    def get_absolute_url(self):
        return "/topics/%s/" % self.title

class Log(models.Model):
    # Core fields.
    author = models.ForeignKey(User, related_name='log_author')
    content = models.CharField(max_length=250,help_text='Maximum 250 characters.')
    pub_date = models.DateTimeField(default=datetime.datetime.now)
    # Log_Topic_relation.
    topics = models.ManyToManyField(Topic,editable=False, blank=True)
    # Log_User_relation.
    audiences = models.ManyToManyField(User,editable=False, blank=True, through='Log_User_relation')

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = "Logs"

    def __unicode__(self):
        return self.content

    def GetAudienceArray(self):
        arrContent = self.content.split('@')
        arrAudience = []
        for i in range(1,len(arrContent)):
            if arrContent[i].strip()!='':
                p1 = arrContent[i].find(' ')
                if p1 != -1:
                    p2 = arrContent[i].find('#')
                    if p2!= -1 and arrContent[i][:p2].strip()!= '':
                        if arrAudience.count(arrContent[i][:p2].strip()) == 0:
                            arrAudience.append(arrContent[i][:p2].strip())
                    elif arrContent[i][:p1].strip()!= '':
                        if arrAudience.count(arrContent[i][:p1].strip()) == 0:
                            arrAudience.append(arrContent[i][:p1].strip())
                else:
                    p2 = arrContent[i].find('#')
                    if p2!= -1  and arrContent[i][:p2].strip()!= '':
                        if arrAudience.count(arrContent[i][:p2].strip()) == 0:
                            arrAudience.append(arrContent[i][:p2].strip())
                    elif arrContent[i].strip()!= '' and arrAudience.count(arrContent[i].strip()) == 0:
                            arrAudience.append(arrContent[i].strip())                  
        return arrAudience

    def GetTopicArray(self):
        arrContent = self.content.split('#')
        arrTopics = []
        for i in range(1,len(arrContent)):
            if arrContent[i].strip()!='':
                p1 = arrContent[i].find(' ')
                if p1 != -1:
                    p2 = arrContent[i].find('@')
                    if p2 >0 and arrContent[i][:p2].strip()!= '':
                        if arrTopics.count(arrContent[i][:p2].strip()) == 0:
                            arrTopics.append(arrContent[i][:p2].strip())
                    elif p2 == -1 and arrContent[i][:p1].strip()!= '':
                        if arrTopics.count(arrContent[i][:p1].strip()) == 0:
                            arrTopics.append(arrContent[i][:p1].strip())
                else:
                    p2 = arrContent[i].find('@')
                    if p2 >0 and arrContent[i][:p2].strip()!= '':
                        if arrTopics.count(arrContent[i][:p2].strip()) == 0:
                            arrTopics.append(arrContent[i][:p2].strip())
                    elif p2 == -1 and arrContent[i].strip()!= '':
                        if arrTopics.count(arrContent[i].strip()) == 0:
                            arrTopics.append(arrContent[i].strip())
        return arrTopics
    
    def save(self, *args, **kwargs):
        #Call the "real" save() method
        super(Log, self).save(*args, **kwargs)
        
        # get topics array
        arrTopics = self.GetTopicArray()
        
        # adding topics array
        for topicTitle in arrTopics:
            # get or create topic
            topic = Topic.objects.get_or_create(title=topicTitle)[0]
            # update gross number
            topic.gross = topic.gross + 1
            topic.save()
            # create relation
            self.topics.add(topic)            
        
        # get Audience array
        arrAudience = self.GetAudienceArray()
        for audience in arrAudience:
            try:
                user = User.objects.get(username=audience)
                relation = Log_User_relation(log=self,user=user)
                relation.save()
            except User.DoesNotExist:
                continue
            
        

    def get_absolute_url(self):
        return "/%s/" % (self.author.lower())


class Log_User_relation(models.Model):
    log = models.ForeignKey(Log)
    user = models.ForeignKey(User)
    date_created = models.DateField(default=datetime.datetime.now)
    IsAccepted = models.BooleanField(default=0)
    
class User_Friend_relation(models.Model):
    user = models.ForeignKey(User)
    friend = models.ForeignKey(User,related_name='friend')
    date_created = models.DateField(default=datetime.datetime.now)
    # IsShowed will be 1 after user saw this message.
    IsShowed = models.BooleanField(default=0)
